package com.retailers.generator.service.Impl.mybaitsv1.service;

import com.retailers.generator.bean.ColumnBean;
import com.retailers.generator.bean.TableBean;
import com.retailers.generator.service.Impl.AbsMybatisGen;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;

/**
 * @description:  mybatis 相关代码生成
 * @author: honglei
 * @time: 2021/3/23 0023 14:48
 */
@Service
public class MybatisGenerateService extends AbsMybatisGen {



    public Connection getConnection() throws Exception{
        Properties props =new Properties();
        props.put("user", config.getUserName());
        props.put("password", config.getPassword());
        props.put("useInformationSchema","true"); //表注释
        Class.forName(config.getDriver());
        Connection connection= DriverManager.getConnection(config.getUrl(),props );
        return connection;
    }


    @Override
    public List<TableBean> tablesList() throws Exception {
        List<TableBean> list=new ArrayList<>();
        Connection connection = getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        ResultSet rs = databaseMetaData.getTables(connection.getCatalog(), config.getUserName(),
                null, new String[]{"TABLE"});

        while(rs.next()) {
            TableBean tableBean=new TableBean();
            tableBean.setTableName(rs.getString("TABLE_NAME"));
            tableBean.setComments(rs.getString("REMARKS"));
            tableBean.setClassName(tableToJava(tableBean.getTableName(),""));
            list.add(tableBean);
        }
        rs.close();
        connection.close();
        return list;
    }



    @Override
    public List<ColumnBean> getColumns(String table) throws Exception {
        List<ColumnBean> list=new ArrayList<>();
        Connection connection = getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        ResultSet resultSet = databaseMetaData.getColumns(null,"%", table,"%");

        while(resultSet.next()){
            ColumnBean columnBean=new ColumnBean();
            columnBean.setColumnName(resultSet.getString("COLUMN_NAME"));
            columnBean.setColumnType(resultSet.getString("TYPE_NAME"));
            columnBean.setComments(resultSet.getString("REMARKS"));
        //    columnBean.setAttrName(columnToJava(columnBean.getColumnName()));
            columnBean.setAttrname(replaceUnderLine2UpperCase(columnBean.getColumnName()));
            list.add(columnBean);
        }
        resultSet.close();
        connection.close();
        return list;
    }


}
